﻿using AutoMapper;
using AutoMapper.QueryableExtensions;
using Gridify.EntityFramework;
using Microsoft.EntityFrameworkCore;

namespace Gridify.WebAPI.Extensions
{
	public static class GridifyExtensions
	{
		public static Paging<TDestination> GridifyTo<TSource, TDestination>(
			this IQueryable<TSource> query, IMapper autoMapper, IGridifyQuery gridifyQuery, IGridifyMapper<TSource>? mapper = null)
		{
			var res = query.GridifyQueryable(gridifyQuery, mapper);
			return new Paging<TDestination>(res.Count, res.Query.ProjectTo<TDestination>(autoMapper.ConfigurationProvider).ToList());
		}
		
		// only if you have Gridify.EntityFramework package installed.
		public static async Task<Paging<TDestination>> GridifyToAsync<TSource, TDestination>(
			this IQueryable<TSource> query, IMapper autoMapper, IGridifyQuery gridifyQuery, IGridifyMapper<TSource>? mapper = null)
		{
			var res = await query.GridifyQueryableAsync(gridifyQuery, mapper);
			return new Paging<TDestination>(res.Count, await res.Query.ProjectTo<TDestination>(autoMapper.ConfigurationProvider).ToListAsync());
		}
	}
}
